/*********************************************************************************
 *      Copyright:  (C) 2025 TBW
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(18/05/25)
 *         Author:  huang zixaio <2027838269@qq.com>
 *      ChangeLog:  1, Release initial version on "18/05/25 16:32:11"
 *                 
 ********************************************************************************/
#include "logger.h"
#include "ds18b20.h"

#define BUFSIZE 128

int ds18b20_get_tempareture(float *temperature)
{

	int						rv;
	char					buf[BUFSIZE];
	char					*start = NULL;
	char					temp[32];
	char					*right_temperature = NULL;
	char					*error_info = "Received wrong temperature!";

	int                		 ds18b20_fd = -1;
    DIR                 	*ds18b20_dir = NULL;
    struct dirent       	*direntp = NULL;
    char                	chip_sn[32] = {0};
    int                 	found = 0;
    char               		 ds18b20_path[64] = {0};
    char                	*w1_path = "/sys/bus/w1/devices";

	ds18b20_dir = opendir(w1_path);
    if(ds18b20_dir == NULL)
    {
        log_error("open %s failure:%s\n", w1_path, strerror(errno));
        goto out;
    }

    while(NULL != (direntp = readdir(ds18b20_dir)) )
    {
        if(strstr(direntp->d_name, "28-") )
        {
            strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
            //log_debug("find '28-', d_name:%s, chipset:%s\n", direntp->d_name, chip_sn);
            found = 1;
        }
    }

    closedir(ds18b20_dir);

    if(!found)
    {
        log_error("Can not find ds18b20 chipset\n");
        goto out;
    }

    snprintf(ds18b20_path, sizeof(ds18b20_path), "%s/%s/w1_slave", w1_path, chip_sn);

    //log_debug("da18b20 path:%s, strlen:%d\n", ds18b20_path, strlen(ds18b20_path));

	ds18b20_fd = open(ds18b20_path, O_RDONLY);
    if(ds18b20_fd < 0)
    {
        log_error("open ds18b20 file failure:%s\n", strerror(errno));
        goto out;
    }



	lseek(ds18b20_fd, 0, SEEK_SET);

	memset(buf, 0, sizeof(buf));

	rv = read(ds18b20_fd, buf, sizeof(buf));
    if(rv < 0)
    {
        log_error("read data failure:%s\n", strerror(errno));
        goto out;
    }

	if( (right_temperature = strstr(buf, "YES")) != NULL ) //not affected
    {
        /* **********get rights temperature***********  */
        start = strstr(buf, "t=");
        start += 2;

		*temperature = atof(start)/1000;

		/* string temperature
        memset(temp, 0, sizeof(temp));
        memcpy(temp, start, strlen(start) + 1);
        temp[strlen(temp) - 1] = '\0';
		snprintf(data->temperature, sizeof(data->temperature), "%s", temp);
		*/

        return 0;
    }
	else//affected
    {
        /* **********get error temperature***********  */

		log_warn("get wrong temperature\n");
		goto out;
    }

out:
	if(ds18b20_fd > 0)
		close(ds18b20_fd);
	return -1;
}

